# -*- coding: utf-8 -*-
"""
@Time    : 2021/6/8 15:40
@Author  : Corey
"""
from gui.custom_widget.result_dialog import ResultDialog
from PyQt5.QtWidgets import QApplication, QDesktopWidget, QAbstractItemView, QHeaderView, QTableWidgetItem, QMessageBox
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QColor
from PyQt5.QtChart import (QChart, QChartView, QBarSeries, QBarSet, QBarCategoryAxis, QValueAxis, QSplineSeries)
from my_thread.save_img_thread import WriteImgThread
from my_thread.save_csv_thread import WriteExcel
from matplotlib import pyplot as plt
import sys
import csv
import os
import numpy as np
from utils.log_util import loggings


class ResultAction(ResultDialog):
    def __init__(self):
        super(ResultAction, self).__init__()
        self.headLabels = []
        # self.plot_ui = None
        self.table_handle = self.table_area.tableWidget
        self.plot_statu = 0
        self.grid_statu = 1
        self.img_statu = 1
        self.single_point = 1
        self.file_img_info = None
        self.file_data_info = None
        self.plot_label_dict = {}
        self.auto_size()

    def auto_size(self):
        screen = QDesktopWidget().screenGeometry()
        width_size = screen.width()
        height_size = screen.height()
        self.resize(width_size, height_size)

    def _init_table(self, headLabels):  # 测试开始前初始化表格
        self.headLabels = headLabels
        self.table_handle.setColumnCount(len(self.headLabels))
        self.table_handle.setHorizontalHeaderLabels(self.headLabels)
        self.table_handle.clearContents()
        self.table_handle.setRowCount(0)
        self.table_handle.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOn)
        self.table_handle.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
        for label_index in range(len(headLabels)):
            self.table_handle.horizontalHeader().setSectionResizeMode(label_index, QHeaderView.ResizeToContents)
        self.table_handle.setEditTriggers(QAbstractItemView.NoEditTriggers)
        self.table_handle.setSelectionMode(QAbstractItemView.SingleSelection)  # 设置只能选中一行
        self.table_handle.setSelectionBehavior(QAbstractItemView.SelectRows)
        QApplication.processEvents()
        self.spot_data_list = []
        if self.img_statu:
            self.plot_ui.cv_plot._clear_plot()

    def _spot_data_finish(self, file_data_info):  # 单点模式存储数据
        self.save_csv_thread = WriteExcel(self.headLabels, self.spot_data_list, file_data_info)  # sweep存数据
        self.save_img_thread = WriteImgThread(self.headLabels, self.spot_data_list, file_data_info)  # sweep存数据
        # self.save_img_thread.Data.connect(self._draw_plot)
        self.save_csv_thread.start()
        self.save_img_thread.start()

    def _draw_plot(self, result_dict, title, x_label, y_label, file_path=None, show_log=False, y_invert=False):
        try:
            if self.img_statu:
                self.plot_ui._setAutoHeight(len(result_dict))
                self.plot_ui.cv_plot.show_log = show_log
                self.plot_ui.cv_plot.y_invert = y_invert
                self.plot_ui.cv_plot.plot(result_dict[0], result_dict[1], title, x_label, y_label)
                self.plot_ui.cv_tool.save_img(file_path)
                if self.plot_ui.isHidden():
                    self.plot_ui.showMaximized()
        except Exception as e:
            loggings.error("_draw_plot" + str(e))

    def _refresh_table_data(self, data_dict, path_file):
        # 判断测试错误0
        try:
            self.table_handle.clearContents()
            self.table_handle.setHorizontalHeaderLabels([data_dict["test"].x_label, data_dict["test"].y_label])
            data = data_dict["test"].test_result
            # row_count = self.table_handle.rowCount()
            # print(row_count)
            self.table_handle.setRowCount(len(data[0]))
            # self.table_handle.selectRow(row_count)
            # print(row_list)
            new_data = np.transpose(np.array(data))
            with open(path_file, "w", newline="") as fw:
                csvObj = csv.writer(fw)
                # csvObj.writerow(self.label_list)
                for row in new_data:
                    csvObj.writerow(row)
            for row in range(len(new_data)):
                for col in range(len(new_data[0])):
                    self.table_handle.setItem(row, col, QTableWidgetItem(str(new_data[row][col])))
        except Exception as e:
            loggings.error("_refresh_table_data" + str(e))

    def _plot_titles(self):
        self.plot_area.sc.xlabel(self.plot_label_dict["xlabel"])
        self.plot_area.sc.ylabel(self.plot_label_dict["ylabel"])
        self.plot_area.sc.title_MPL(self.plot_label_dict["title"])

    def _refresh_plot_data(self, plot_list):
        if self.plot_statu:
            self.plot_area.sc.cla_plot()
            self._plot_titles()
            self.plot_area.sc.plotleft(plot_list[0], plot_list[1])
            self.plot_area.scntb.save_img(self.file_img_info)


if __name__ == '__main__':
    app = QApplication(sys.argv)
    window = ResultAction()
    window.showMaximized()
    sys.exit(app.exec())
